import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { constantRoutes } from '@/router/modules/routeRecordRaw'
import type { App } from 'vue'

const mode = import.meta.env.VITE_ROUTER_MODE
import { NO_RESET_WHITE_LIST } from '@/constants'
// 路由模式
const routerMode = {
  hash: () => createWebHashHistory(),
  history: () => createWebHistory()
}
const router = createRouter({
  history: routerMode[mode](),
  routes: [...constantRoutes] as RouteRecordRaw[],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 全局注册 router
export const setupRouter = (app: App) => {
  app.use(router)
}

/**
 * @description 重置路由
 **/
export const resetRouter = (): void => {
  router.getRoutes().forEach(route => {
    const { name } = route
    if (name && !NO_RESET_WHITE_LIST.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}
export default router
